package com.cskaoyan.market.admin.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.cskaoyan.market.admin.service.AdminConfigService;
import com.cskaoyan.market.db.domain.MarketSystem;
import com.cskaoyan.market.db.domain.MarketSystemExample;
import com.cskaoyan.market.db.mapper.MarketSystemMapper;
import com.cskaoyan.market.util.MyBatisUtil;

/**
 * @author BlackFlame33
 * @date 2023/03/22
 **/
public class AdminConfigServiceImpl implements AdminConfigService {
    @Override
    public Map<String, String> getMallConfig() {
        SqlSession session = MyBatisUtil.getSession();
        MarketSystemMapper mapper = session.getMapper(MarketSystemMapper.class);
        MarketSystemExample marketSystemExample = new MarketSystemExample();
        marketSystemExample.or().andKeyNameLike("%_mall_%");
        List<MarketSystem> marketSystems = mapper.selectByExample(marketSystemExample);
        Map<String, String> data = new HashMap<>();
        for (MarketSystem marketSystem : marketSystems) {
            data.put(marketSystem.getKeyName(), marketSystem.getKeyValue());
        }
        return data;
    }

    @Override
    public int updateMallConfig(Map<String, String> configMap) {
        SqlSession session = MyBatisUtil.getSession();
        MarketSystemMapper mapper = session.getMapper(MarketSystemMapper.class);
        List<MarketSystem> marketSystems = mapper.selectByExample(new MarketSystemExample());
        int code = 0;
        try {
            for (MarketSystem marketSystem : marketSystems) {
                if (configMap.containsKey(marketSystem.getKeyName())) {
                    marketSystem.setKeyValue(configMap.get(marketSystem.getKeyName()));
                    mapper.updateByPrimaryKey(marketSystem);
                }
            }
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
            code = -1;
            return code;
        } finally {
            session.close();
        }
        return code;
    }
}